package com.gxa.hualian.web.servlet;

import com.gxa.hualian.util.JsonResult;
import com.gxa.hualian.util.ResponseUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

/**
 * 文件上传
 * @author Administrator
 */
@WebServlet(name = "UploadServlet", value = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置字符集
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //1.通过request获取文件

        //使用UploadFile组件实现
        //获取文件内容
        //判断表单元素的类型
        //文件的写操作
        //完成在服务器中文件的存储
        //文件对象工厂
        FileItemFactory factory = new DiskFileItemFactory();

        // 文件上传处理器
        ServletFileUpload upload = new ServletFileUpload(factory);
        // 解析请求信息
        List<FileItem> items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        }
        // 对请求信息进行判断
        //使用迭代器完成
        Iterator iter = items.iterator();
        String fileName=null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // 信息为文件格式
            //当判断上传的内容非表单元素,那么意味着当前的内容为上传文件可喜
            if (!item.isFormField()) {
                //获得上传图片的名称  获取文件名
                 fileName = item.getName();
                int index = fileName.lastIndexOf("\\");
                fileName = fileName.substring(index + 1);

                //获取后缀
                int pos = fileName.lastIndexOf(".");
                //获取后缀
                String ext = fileName.substring(pos);

                //  request.setAttribute("realFileName", fileName);
                String basePath = request.getSession().getServletContext().getRealPath("/static/images/upload");
                // System.out.println(basePath);//打印当前位置
                //使用UUID生成唯一字符串,充当文件名
                fileName= UUID.randomUUID().toString().replaceAll("-","")+ext;
                File file = new File(basePath, fileName);
                try {
                    item.write(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }


            //2.返回 服务器中的图像的路径
            JsonResult jsonResult=new JsonResult();
            jsonResult.setCode("1");
            jsonResult.set("img","/static/images/upload/"+fileName);
            //2. 声明ResponseUtil对象,完成写操作
            ResponseUtil responseUtil = new ResponseUtil(response,jsonResult);
            responseUtil.write();
        }
    }
}
